new 做了什麼事?


Posted by YongChenSu on 2020-12-09

先備知識 call()

function test() {
  console.log(this)
}

test.call('123') // {string: '123'}
test.call({}) // {}

new 關鍵字做的事

  1. 產生新的 obj
  2. call constructor,把 obj 當作 this 丟進去,便完成初始化的物件
  3. 設定 proto 到指定的 prototype
  4. 回傳 obj
  5. 完成 instance
function Dog(name) {
  this.name = name
}

Dog.prototype.getName = function() {
  return this.name
}

Dog.prototype.sayHello = function() {
  console.log(this.name)
}

var d = new Dog('hi')
var b = newDog('hello')

function newDog(name) {
  var obj = {}
  Dog.call(obj, name)
  console.log(obj) // {name: 'hello'}
  obj.__proto__ = Dog.prototype
  return obj
}

b.sayHello() // hello
console.log(b.getName()) // hello


參考資源


#程式導師實驗計畫第四期 #前端 #new







Related Posts

【React】- React 怎麼做成 GitHub page?

【React】- React 怎麼做成 GitHub page?

巨量資料 & 機器學習基礎教學

巨量資料 & 機器學習基礎教學

redis 套件的 Property 'on' does not exist on type 'RedisClientType'

redis 套件的 Property 'on' does not exist on type 'RedisClientType'


Comments